package me.hekr.iotos.api.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import me.hekr.iotos.api.enums.CheckType;
import me.hekr.iotos.api.enums.DataType;

@JsonTypeName("ENUM")
public class DataValueEnumChecker implements DataValueChecker {
  private List<ModelParamValue<Object>> values;

  @Override
  @JsonIgnore
  public boolean isValid(DataType dataType, Object value) {
    DataType valueDataType = DataType.fromValue(value);
    if (!DataType.isValid(dataType, value)) {
      return false;
    } else {
      Iterator var4 = this.values.iterator();

      ModelParamValue v;
      do {
        if (!var4.hasNext()) {
          return false;
        }

        v = (ModelParamValue) var4.next();
      } while (!valueDataType.isEq(v.getValue(), value));

      return true;
    }
  }

  @Override
  @JsonIgnore
  public boolean canConvertTo(DataType dataType) {
    List<ModelParamValue<Object>> result = new ArrayList(this.values.size());
    Iterator var3 = this.values.iterator();

    while (var3.hasNext()) {
      ModelParamValue o = (ModelParamValue) var3.next();

      try {
        Object v = dataType.convert(o.getValue());
        result.add(new ModelParamValue(v, o.getDesc()));
      } catch (Exception var6) {
        return false;
      }
    }

    this.values.clear();
    this.values.addAll(result);
    return true;
  }

  @Override
  public boolean valid(DataType dataType) {
    return this.values == null
        ? false
        : this.values.stream()
            .allMatch(
                (v) -> {
                  if (v != null && v.getValue() != null) {
                    if (dataType == DataType.FLOAT
                        && DataType.fromValue(v.getValue()) == DataType.INT) {
                      return true;
                    } else {
                      return DataType.fromValue(v.getValue()) == dataType;
                    }
                  } else {
                    return false;
                  }
                });
  }

  @Override
  public CheckType getType() {
    return CheckType.ENUM;
  }

  @Override
  public String toString() {
    String str =
        this.values == null
            ? "[]"
            : "["
                + (String)
                    this.values.stream()
                        .map(
                            (m) -> {
                              return m.getValue() + ":" + m.getDesc();
                            })
                        .collect(Collectors.joining(", "))
                + "]";
    return "enum check, enum values:" + str;
  }

  public DataValueEnumChecker() {}

  public List<ModelParamValue<Object>> getValues() {
    return this.values;
  }

  public void setValues(List<ModelParamValue<Object>> values) {
    this.values = values;
  }
}
